﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace CodeBackup.Code
{
    public class IniFile
    {
        private string fileName;

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileInt(string lpAppName, string lpKeyName, int nDefault, string lpFileName);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);

        [DllImport("kernel32")]
        private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);

        // 段信息的获取  //读取一个ini 文件中的所有段    
        [DllImport("kernel32", EntryPoint = "GetPrivateProfileSectionNamesW", CharSet = CharSet.Unicode)]
        private extern static int getSectionNames([MarshalAs(UnmanagedType.LPWStr)] string szBuffer, int nlen, string filename);
        //读取段里的所有数据    
        [DllImport("kernel32", EntryPoint = "GetPrivateProfileSectionW", CharSet = CharSet.Unicode)]
        private extern static int getSectionValues(string Section, [MarshalAs(UnmanagedType.LPWStr)] string szBuffer, int nlen, string filename);
        public IniFile(string filename)
        {
            this.fileName = filename;
        }

        public void DelKey(string section, string key)
        {
            WritePrivateProfileString(section, key, null, this.fileName);
        }

        public void DelSection(string section)
        {
            WritePrivateProfileString(section, null, null, this.fileName);
        }

        public DateTime GetDateTime(string section, string key, DateTime def)
        {
            DateTime result = def;

            StringBuilder lpReturnedString = new StringBuilder(0x400);
            GetPrivateProfileString(section, key, def.ToString(), lpReturnedString, 0x400, this.fileName);
            string getdatetime = lpReturnedString.ToString();

            if (lpReturnedString.Length != 0)
            {
                try
                {
                    result = Convert.ToDateTime(getdatetime);
                }
                catch
                {
                    result = def;
                }
            }

            return result;
        }

        public int GetInt(string section, string key, int def)
        {
            return GetPrivateProfileInt(section, key, def, this.fileName);
        }

        public string GetString(string section, string key, string def)
        {
            StringBuilder lpReturnedString = new StringBuilder(0x400);
            GetPrivateProfileString(section, key, def, lpReturnedString, 0x400, this.fileName);
            return lpReturnedString.ToString();
        }

        public bool GetBool(string section, string key, bool Default)
        {
            int def;

            def = Default ? 1 : 0;
            int result = GetPrivateProfileInt(section, key, def, this.fileName);

            if (result == 0) return false;
            if (result == 1) return true;
            return Default;
        }

        public void WriteInt(string section, string key, int iVal)
        {
            WritePrivateProfileString(section, key, iVal.ToString(), this.fileName);
        }

        public void WriteDateTime(string section, string key, DateTime dVal)
        {
            WritePrivateProfileString(section, key, dVal.ToString(), this.fileName);
        }

        public void WriteString(string section, string key, string strVal)
        {
            WritePrivateProfileString(section, key, strVal, this.fileName);
        }

        public void WriteBool(string section, string key, bool Value)
        {
            int iVal = Value ? 1 : 0;

            WritePrivateProfileString(section, key, iVal.ToString(), this.fileName);
        }

        /// <summary>  /// 读取所有段名  /// </summary>   
        public string[] SectionNames
        {
            get
            {
                string buffer = new string('\0', 32768);
                int nlen = getSectionNames(buffer, 32768 - 1, fileName) - 1;
                if (nlen > 0)
                {
                    return buffer.Substring(0, nlen).Split('\0');
                }
                return null;
            }
        }


        /// </summary>          
        /// <param name="section">段名</param>          
        /// <param name="bufferSize">读取的数据大小(字节)</param>   
        /// <returns>成功则不为null</returns>          
        private string[] SectionValues(string section, int bufferSize)
        {
            string buffer = new string('\0', bufferSize);
            int nlen = getSectionValues(section, buffer, bufferSize, fileName) - 1;
            if (nlen > 0)
            {
                return buffer.Substring(0, nlen).Split('\0');
            }
            return null;
        }
        public string[] SectionValues(string section)
        {
            return SectionValues(section, 32768);
        }


        /// <summary>         
        /// 从一个段中读取其 键-值 数据   /// 
        /// </summary>   
        /// <param name="section">段名</param>   
        /// <param name="bufferSize">读取的数据大小(字节)</param>  /// 
        /// <returns>成功则不为null</returns>         
        private Dictionary<string, string> SectionValuesEx(string section, int bufferSize)
        {
            string[] sztmp = SectionValues(section, bufferSize);
            if (sztmp != null)
            {
                int ArrayLen = sztmp.Length;
                if (ArrayLen > 0)
                {
                    Dictionary<string, string> dtRet = new Dictionary<string, string>();
                    for (int i = 0; i < ArrayLen; i++)
                    {
                        int pos1 = sztmp[i].IndexOf('=');
                        if (pos1 > 1)
                        {
                            int nlen = sztmp[i].Length;
                            // 取键名,键值     
                            pos1++;
                            if (pos1 < nlen)
                                dtRet.Add(sztmp[i].Substring(0, pos1 - 1), sztmp[i].Substring(pos1, nlen - pos1));
                        }
                    }
                    return dtRet;
                }
            }
            return null;
        }
        public Dictionary<string, string> SectionValuesEx(string section)
        {
            return SectionValuesEx(section, 32768);
        }

    }
}
